/**
 * @Author: lll
 * @Email:li.lele@vpclub.cn
 * @Date: create in 2020/6/30
 */
package cn.vpclub.admin.handle;

import cn.vpclub.admin.exception.NoPermissionException;
import cn.vpclub.admin.exception.NoTokenException;
import cn.vpclub.admin.exception.TokenWrongException;
import cn.vpclub.admin.util.BaseResponse;
import cn.vpclub.admin.util.ResponseCodeEnum;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;

//import org.springframework.http.converter.HttpMessageNotReadableException;
//import org.springframework.security.authentication.BadCredentialsException;
//import org.springframework.security.authentication.DisabledException;

/**
 * 全局异常拦截
 *
 * @author Administrator
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponse handlerException(Exception e) {
        if (e instanceof NoHandlerFoundException) {
            log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getHttpMethod(), ((NoHandlerFoundException) e).getRequestURL());
            return BaseResponse.info(ResponseCodeEnum.NOTFOUND, null);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), (((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
            return BaseResponse.info(ResponseCodeEnum.METHODERROR, null);
        } else if (e instanceof NoTokenException) {
            log.error("【全局异常拦截】自定义NoTokenException：请求错误信息 {}", e.getMessage());
            return BaseResponse.info(ResponseCodeEnum.NoToken, null);
        } else if (e instanceof TokenWrongException || e instanceof JWTDecodeException) {
            log.error("【全局异常拦截】没有根据token查询到用户名或者无法解析token异常：请求错误信息 {}", e.getMessage());
            return BaseResponse.info(ResponseCodeEnum.TokenWrong, null);
        } else if (e instanceof IllegalArgumentException) {
            log.error("【全局异常拦截】非法访问字符异常：请求错误信息 {}", e.getMessage());
            return BaseResponse.info(ResponseCodeEnum.IllegalArgumentException, null);
        } else if (e instanceof TokenExpiredException) {
            log.error("【全局异常拦截】Token超时异常：请求错误信息 {}", e.getMessage());
            return BaseResponse.info(ResponseCodeEnum.TokenExpiredException, null);
        } else if (e instanceof MethodArgumentNotValidException) {
            log.error("【全局异常拦截】前端入参异常：请求错误信息 {}", e.getMessage());
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            List<ObjectError> errors = methodArgumentNotValidException.getBindingResult().getAllErrors();
            StringBuilder stringBuilder = new StringBuilder();
            errors.stream().forEach(res -> {
                stringBuilder.append(res.getDefaultMessage()).append(",");
            });
            return BaseResponse.customInfo(666, stringBuilder.substring(0, stringBuilder.length() - 1), null);
        } else if (e instanceof NoPermissionException) {
            log.error("【全局异常拦截】无权限：请求错误信息 {}", e.getMessage());
            return BaseResponse.info(ResponseCodeEnum.NoPermission, null);
        }
        log.error("【全局异常拦截】: 上述异常没有被拦截，再此拦截所有异常，统一返回下述500，异常信息 {} ", e.getMessage());
        return BaseResponse.info(ResponseCodeEnum.FAIL, null);
    }
}
